package com.sxf.controller.blog.admin;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;

import com.sxf.common.tools.CommonTools;
import com.sxf.common.tools.Constants;
import com.sxf.controller.SuperController;
import com.sxf.domain.Term;
import com.sxf.domain.TermRelationships;
import com.sxf.domain.TermTaxonomy;
import com.sxf.domain.TermVO;
import com.sxf.formbean.TermForm;
import com.sxf.mybatis.page.Pagination;
import com.sxf.querybean.TermQuery;
import com.sxf.querybean.TermRelationshipsQuery;
import com.sxf.service.TermRelationshipsService;
import com.sxf.service.TermService;
import com.sxf.service.TermTaxonomyService;
import com.sxf.view.datatables.DataTables;
import com.sxf.view.datatables.DataTablesReturn;
import com.sxf.view.datatables.DatatablesHelp;

/**
 * @author phsxf01
 * 
 */
@Controller
@RequestMapping("blog/admin/term")
public class TermController extends SuperController {
	@Resource(name = "termService")
	private TermService termService;
	@Resource(name = "termRelationshipsService")
	private TermRelationshipsService termRelationshipsService;
	@Resource(name = "termTaxonomyService")
	private TermTaxonomyService termTaxonomyService;

	@RequestMapping("/toCategory")
	public ModelAndView toCategory() throws Exception {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("blog/admin/term");
		List<TermVO> list = listAjax(Constants.TAXONOMY_POST_CATEGORY);
		mav.addObject("parentTermList", list);
		mav.addObject("taxonomy", Constants.TAXONOMY_POST_CATEGORY);
		return mav;
	}

	@RequestMapping("/toTag")
	public ModelAndView toTag() throws Exception {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("blog/admin/term");
		List<TermVO> list = listAjax(Constants.TAXONOMY_POST_TAG);
		mav.addObject("parentTermList", list);
		mav.addObject("taxonomy", Constants.TAXONOMY_POST_TAG);
		return mav;
	}

	@RequestMapping("/toLinkCategory")
	public ModelAndView toLinkCategory() throws Exception {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("blog/admin/term");
		List<TermVO> list = listAjax(Constants.TAXONOMY_LINKA_CATEGORY);
		mav.addObject("parentTermList", list);
		mav.addObject("taxonomy", Constants.TAXONOMY_LINKA_CATEGORY);
		return mav;
	}

	@RequestMapping("/toTerm")
	public ModelAndView toTerm() throws Exception {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("blog/admin/term");
		List<TermVO> list = listAjax("");
		mav.addObject("parentTermList", list);
		mav.addObject("taxonomy", "term");
		return mav;
	}

	/**
	 * 跳转到修改页面
	 * 
	 * @param termId
	 * @param taxonomy
	 * @return
	 */
	@RequestMapping("/toEdit")
	public ModelAndView toEdit(
			@RequestParam(value = "termId", required = true) Long termId)
			throws Exception {
		ModelAndView mav = new ModelAndView();
		if (termId != null) {
			TermQuery query = new TermQuery();
			query.setId(termId);
			TermVO term = termService.queryOne(query);
			if (term != null && term.getSlug() != null) {
				term.setSlug(URLDecoder.decode(term.getSlug(), "UTF-8"));
			}
			mav.addObject("term", term);
			mav.addObject("taxonomy", term.getTaxonomy());
			List<TermVO> list = listAjax(term.getTaxonomy());
			mav.addObject("parentTermList", list);
		}
		mav.setViewName("blog/admin/term_edit");
		return mav;
	}

	@RequestMapping("/pageAjax")
	@ResponseBody
	public DataTablesReturn pageAjax(
			@RequestParam(value = "taxonomy", required = true) String taxonomy,
			@RequestParam(value = "page", required = false) String page,
			@RequestParam(value = "rows", required = false) String rows,
			WebRequest request) throws Exception {
		DataTablesReturn tableReturn = null;
		String dtjson = request.getParameter("dtjson");
		if (StringUtils.hasText(dtjson)) {

			DataTables dt = DatatablesHelp.getDataTable(dtjson);

			Pagination<TermVO> termPage = null;
			TermQuery query = new TermQuery();
			query.setTaxonomy(taxonomy);
			if (dt.getDisplayLength() != null) {
				query.setLimit(dt.getDisplayLength());
			}
			if (dt.getDisplayStart() != null) {
				query.setOffset(dt.getDisplayStart());
			}
			if (StringUtils.hasText(dt.getSearch())) {
				query.setName(dt.getSearch());
			}
			if (StringUtils.hasText(taxonomy)) {
				termPage = termService.queryPage(query);
			}
			tableReturn = DatatablesHelp.getDataTableReturn(termPage, dt);
		}
		return tableReturn;
	}

	@RequestMapping("/listAjax")
	@ResponseBody
	public List<TermVO> listAjax(
			@RequestParam(value = "taxonomy", required = true) String taxonomy)
			throws Exception {
		List<TermVO> termList = null;
		if (StringUtils.hasText(taxonomy)) {
			TermQuery query = new TermQuery();
			query.setTaxonomy(taxonomy);
			termList = termService.queryList(query);
		}
		return termList;
	}

	@RequestMapping("/doAddPostCategoryAjax")
	@ResponseBody
	public ModelAndView doAddPostCategoryAjax(WebRequest request)
			throws Exception {
		ModelAndView mav = new ModelAndView();
		String newcategory = request.getParameter("newcategory");
		if (StringUtils.hasText(newcategory)) {
			String newcategory_parent = request
					.getParameter("newcategory_parent");
			TermForm tf = new TermForm();
			tf.setName(newcategory.trim());
			tf.setDescription("");
			tf.setSlug(URLEncoder.encode(newcategory, "UTF-8"));
			tf.setParent(Long.valueOf(newcategory_parent));
			tf.setTaxonomy(Constants.TAXONOMY_POST_CATEGORY);
			addOrUpdate(tf);
		}
		return mav;
	}

	/**
	 * 添加文章标签
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/doAddPostTagAjax")
	@ResponseBody
	public ModelAndView doAddPostTagAjax(WebRequest request) throws Exception {
		ModelAndView mav = new ModelAndView();
		String newtags = request.getParameter("newtag[post_tag]");
		if (StringUtils.hasText(newtags)) {
			String[] strArr = newtags.trim().split("[,]");
			for (String str : strArr) {
				if (StringUtils.hasText(str)) {
					TermForm tf = new TermForm();
					tf.setName(str.trim());
					tf.setDescription("");
					tf.setSlug(URLEncoder.encode(str, "UTF-8"));
					tf.setParent(0l);
					tf.setTaxonomy(Constants.TAXONOMY_POST_TAG);
					addOrUpdate(tf);
				}
			}
		}
		return mav;
	}

	@RequestMapping("/doAddLinkCategoryAjax")
	@ResponseBody
	public ModelAndView doAddLinkCategoryAjax(WebRequest request)
			throws Exception {
		ModelAndView mav = new ModelAndView();
		String newcategory = request.getParameter("newcat");
		if (StringUtils.hasText(newcategory)) {
			TermForm tf = new TermForm();
			tf.setName(newcategory.trim());
			tf.setDescription("");
			tf.setSlug(URLEncoder.encode(newcategory, "UTF-8"));
			tf.setParent(0l);
			tf.setTaxonomy(Constants.TAXONOMY_LINKA_CATEGORY);
			addOrUpdate(tf);
		}
		return mav;
	}

	@RequestMapping("/doAddOrUpdateAjax")
	@ResponseBody
	public ModelAndView doAddOrUpdateAjax(@ModelAttribute TermForm termForm,
			BindingResult br) throws Exception {
		ModelMap map = new ModelMap();
		if (termForm != null) {
			if (!addOrUpdate(termForm)) {
				map.put("error", "数据有误");
			}
		}
		return getModelAndView(map, "");
	}

	@RequestMapping("/doAddOrUpdate")
	public ModelAndView doAddOrUpdate(@ModelAttribute TermForm tf,
			BindingResult br) throws Exception {
		ModelAndView mav = new ModelAndView();
		if (tf != null) {
			if (!addOrUpdate(tf)) {
				mav.addObject("error", "数据有误");
			}
			if (Constants.TAXONOMY_POST_CATEGORY.equals(tf.getTaxonomy())) {
				mav.setViewName("redirect:/blog/admin/term/toCategory");
			} else if (Constants.TAXONOMY_POST_TAG.equals(tf.getTaxonomy())) {
				mav.setViewName("redirect:/blog/admin/term/toTag");
			}

		}
		return mav;
	}

	/**
	 * 添加术语
	 * 
	 * @param tf
	 * @return
	 * @throws Exception
	 */
	private boolean addOrUpdate(TermForm tf) throws Exception {
		boolean flag = false;
		if (tf != null) {
			if (tf.getTermId() == null
					&& tf.getTaxonomyId() == null
					&& (Constants.TAXONOMY_POST_CATEGORY.equals(tf
							.getTaxonomy())
							|| Constants.TAXONOMY_POST_TAG.equals(tf
									.getTaxonomy())
							|| Constants.TAXONOMY_LINKA_CATEGORY.equals(tf
									.getTaxonomy())
							|| Constants.TAXONOMY_POST_TAG.equals(tf
									.getTaxonomy()) || Constants.TAXONOMY_POST_FORMAT
								.equals(tf.getTaxonomy()))) {
				// 添加
				TermTaxonomy tt = new TermTaxonomy();
				Term term = new Term();
				term.setName(tf.getName());
				term.setGroup(0);
				if (StringUtils.hasText(tf.getSlug())) {
					if (CommonTools.hasFullSize(tf.getSlug())) {
						term.setSlug(URLEncoder.encode(tf.getSlug(), "UTF-8"));
					} else {
						term.setSlug(tf.getSlug());
					}
				} else {
					term.setSlug("");
				}
				termService.insert(term);

				tt.setTermId(term.getId());
				if (tf.getParent() != null) {
					tt.setParent(tf.getParent());
				} else {
					tt.setParent(0l);
				}
				tt.setCount(0l);
				if (StringUtils.hasText(tf.getDescription())) {
					tt.setDescription(tf.getDescription());
				} else {
					tt.setDescription("");
				}

				tt.setTaxonomy(tf.getTaxonomy());
				// tt.setCount(tf.getCount());
				termTaxonomyService.insert(tt);
				flag = true;
			} else if (tf.getTermId() != null
					&& tf.getTaxonomyId() != null
					&& (Constants.TAXONOMY_POST_CATEGORY.equals(tf
							.getTaxonomy())
							|| Constants.TAXONOMY_POST_TAG.equals(tf
									.getTaxonomy()) || Constants.TAXONOMY_LINKA_CATEGORY
								.equals(tf.getTaxonomy()))) {
				// 修改

				Term term = new Term();
				term.setId(tf.getTermId());
				if (tf.getName() != null) {
					term.setName(tf.getName());
				}
				if (tf.getSlug() != null) {
					if (CommonTools.hasFullSize(tf.getSlug())) {
						term.setSlug(URLEncoder.encode(tf.getSlug(), "UTF-8"));
					} else {
						term.setSlug(tf.getSlug());
					}

				} else {
					term.setSlug("");
				}
				termService.update(term);

				TermTaxonomy tt = new TermTaxonomy();
				tt.setId(tf.getTaxonomyId());
				tt.setTermId(term.getId());
				if (tf.getParent() != null) {
					tt.setParent(tf.getParent());
				}
				if (tf.getDescription() != null) {
					tt.setDescription(tf.getDescription());
				}
				tt.setTaxonomy(tf.getTaxonomy());
				// tt.setCount(tf.getCount());
				termTaxonomyService.update(tt);
				flag = true;
			}

		}
		return flag;
	}

	@RequestMapping("/delete")
	@ResponseBody
	public String delete(
			@RequestParam(value = "taxonomyId", required = true) Long taxonomyId)
			throws Exception {
		if (taxonomyId != null) {
			TermQuery query = new TermQuery();
			query.setTaxonomyId(taxonomyId);
			TermVO deleteTerm = termService.queryOne(query);
			if (deleteTerm != null) {
				Term term = new Term();
				term.setId(deleteTerm.getId());
				termService.delete(term);
				TermTaxonomy tt = new TermTaxonomy();
				tt.setId(taxonomyId);
				termTaxonomyService.delete(tt);

				TermRelationshipsQuery trsq = new TermRelationshipsQuery();
				trsq.setTermTaxonomyId(taxonomyId);
				List<TermRelationships> trList = termRelationshipsService
						.queryList(trsq);
				if (trList != null && !trList.isEmpty()) {
					for (TermRelationships tr : trList) {
						TermRelationships info = new TermRelationships();
						info.setObjectId(tr.getObjectId());
						info.setTermTaxonomyId(tr.getTermTaxonomyId());
						termRelationshipsService.delete(info);
					}
				}
			}
		}

		return "success";
	}
}
